package com.hebtu.helper.modules.sys.controller;

import com.hebtu.helper.common.utils.H;
import com.hebtu.helper.common.utils.LayuiPage;
import com.hebtu.helper.modules.sys.entity.SysUserEntity;
import com.hebtu.helper.modules.sys.service.SysUserRoleService;
import com.hebtu.helper.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Base64;
import java.util.Map;

/**
 * @author YKF
 * @date 2019/5/25 8:23
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    /**
     * 列表
     */
    @RequestMapping("/list")
    public LayuiPage list(@RequestParam Map<String, Object> params){
        return sysUserService.queryPage(params);
    }

    /**
     * 保存
     * @param sysUserEntity
     * @return
     */
    @RequestMapping("/save")
    public H save(@RequestBody SysUserEntity sysUserEntity) {
        sysUserEntity.setPassword(Base64.getEncoder().encodeToString(sysUserEntity.getPassword().getBytes()));
        return sysUserService.save(sysUserEntity)?H.success("插入成功") : H.error(230,"插入失败");
    }

    /**
     * 根据userId查询实体
     * @param userId
     * @return
     */
    @RequestMapping("/info/{userId}")
    public H info(@PathVariable("userId") Long userId){
        SysUserEntity sysUserEntity=sysUserService.selectById(userId);
        sysUserEntity.setRoleIds(sysUserRoleService.queryRolesByUserID(userId));
        sysUserEntity.setPassword("");
        return sysUserService.selectById(sysUserEntity)!=null?H.success().put("data",sysUserEntity):H.error(203,"未找到");
    }

    /**
     * 修改
     * @param sysUserEntity form表单传递过来的值
     * @return
     */
    @RequestMapping("/update")
    public H update(@RequestBody SysUserEntity sysUserEntity){
        if(!sysUserEntity.getPassword().isEmpty())
            sysUserEntity.setPassword(Base64.getEncoder().encodeToString(sysUserEntity.getPassword().getBytes()));
        return sysUserService.update(sysUserEntity)?H.success():H.error(203,"修改失败");
    }
    /**
     * 根据userId删除
     * @param userId
     * @return
     */
    @RequestMapping("/deleteById/{userId}")
    @Transactional
    public H deleteById(@PathVariable("userId") Long  userId){
        sysUserRoleService.delete(userId);
        return sysUserService.deleteById(userId)? H.success("删除成功"):H.error(230,"删除失败");
    }

    /**
     * 修改状态
     * @param userId
     * @param status
     * @return
     */
    @RequestMapping("/status")
    public H status(Long userId,boolean status) {
        return sysUserService.updataStatus(userId,status)==1? H.success("修改成功") : H.error(230,"修改失败");
    }
}
